package com.kaikeba.dao.impl;

import com.kaikeba.dao.BaseAdminDao;
import com.kaikeba.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * @description:
 * @author: ManolinCoder
 * @time: 2021/8/29
 */
public class AdminDaoMysql implements BaseAdminDao {

    //logintime可以直接用函数获取当前时间（NOW()）
    private static final String SQL_UPDATE_LOGIN_TIME = "update eadmin set logintime=?,loginip=? where username=?";
    private static final String SQL_LOGIN = "select id from eadmin where username=? and password=?";

    /**
     * @param username
     * @param date
     * @param ip
     * @return void
     * @Author LC
     * @Description //TODO 根据用户名，更新登录时间和登录ip
     * @Date 13:56 2021/8/29
     * @Param [username, date, ip]
     */
    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        //1.获取链接
        Connection connection = DruidUtil.getConnection();
        //2.预编译sql语句
        PreparedStatement state = null;
        try {
            state = connection.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            //3.填充参数
            //注意将java.util.Date转换为java.sql.Date
            state.setDate(1,new java.sql.Date(date.getTime()));
            state.setString(2,ip);
            state.setString(3,username);
            //4.执行
            state.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //5.释放资源
            DruidUtil.close(connection,state,null);
        }

    }

    /**
     * @param username
     * @param password
     * @return boolean
     * @Author LC
     * @Description //TODO 管理员登录
     * @Date 13:57 2021/8/29
     * @Param [username, password]
     */
    @Override
    public boolean login(String username, String password) {
        //1.获取链接
        Connection connection = DruidUtil.getConnection();
        //2.预编译sql语句
        PreparedStatement state = null;
        ResultSet resultSet = null;
        try {
            state = connection.prepareStatement(SQL_LOGIN);
            //3.填充参数
            state.setString(1,username);
            state.setString(2,password);
            //4.执行
            resultSet = state.executeQuery();
            //根据查询结果返回
            //调用resultSet.next()，如果查询有结果则游标可以往下移动，返回true
            //如果没有结果则游标无法向下移动返回false
            return resultSet.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //5.释放资源
            DruidUtil.close(connection,state,resultSet);
        }
        return false;
    }
}
